<?php
declare(strict_types=1);
namespace SixShop\Lakala\Service;

use SixShop\Lakala\Config;
use SixShop\Lakala\OpenAPISDK\V3\Api\LakalaNotifyApi;
use SixShop\Lakala\OpenAPISDK\V3\Model\ModelTradeNotify;
use SixShop\Lakala\PaymentProvider;
use SixShop\Payment\Enum\PaymentStatusEnum;
use SixShop\Payment\Model\ExtensionPaymentModel;
use think\facade\Log;
use function SixShop\Core\error_response;
use function SixShop\Core\throw_logic_exception;

class NotifyService
{
    private LakalaNotifyApi $notifyApi;
    public function __construct(private Config $config, private PaymentProvider $paymentProvider)
    {
        $this->notifyApi = new LakalaNotifyApi($this->config->getV3Config());
    }

    public function notify(): void
    {
        $headers = getallheaders();
        $body = file_get_contents('php://input');
        Log::debug('lakala notify headers:{headers}  body:{body}', [
            'headers' => json_encode($headers),
            'body' => $body
        ]);
        $notify = $this->notifyApi->notiApi($headers, $body);
        $inBody = $notify->getOriginalText();
        if (!json_validate($inBody)) {
            throw_logic_exception('lakala notify json error');
        }
        $bodyArr = json_decode($inBody, true);
        $payment = ExtensionPaymentModel::where(['transaction_id' => $bodyArr['trade_no']])->findOrEmpty();
        if ($payment->isEmpty()) {
            throw_logic_exception('lakala notify transaction_id error');
        }
        if ($payment->status != PaymentStatusEnum::PENDING) {
            throw_logic_exception('lakala notify transaction_id status error');
        }
        $this->paymentProvider->query($payment->id);
        Log::debug('lakala notified success {transaction_id}', ['transaction_id' => $payment->transaction_id]);
    }
}